<?php

class MyController extends CController
{
	var $session = NULL;
	var $data = NULL;
	
	var $host_name = NULL;
	var $user = NULL;
	var $website = NULL;
	
	var $route = NULL;
	var $controller_id = NULL;
	var $module_id = NULL;
	
	var $action = NULL;
	var $baseUrl = NULL;
	
	var $webroot = NULL;
		
	function init()
	{
		$this->data = array();
		$this->website = website::model()->find(array("condition"=>"`default` = 1"));
		
		$this->module_id = $this->getModule()->getId();
		$this->route = $this->getRoute();
		$this->controller_id = $this->getId();
		
		$this->host_name = Yii::app()->getRequest()->getHostInfo();
		$this->baseUrl = Yii::app()->baseUrl;
		$this->webroot = Yii::app()->getRequest()->getHostInfo() . Yii::app()->baseUrl;
		
		$this->session = new CDbHttpSession();
		$this->session->connectionID = "db"; 
		$session_time = $this->website["session_time"];
		$this->session->setTimeout($session_time * 60);
		$this->session->open();
		
		// neu ko co default thi chon id = 1
		if (is_null($this->website))
			$this->website = website::model()->findByPk(1);
		
		if ( ! $this->check_user_logged_in())
		{
			$this->redirect(array('/system/login/index'));
			
		}else{
			
			// TODO
			$username = $this->session["username"];
			
			$this->user = user::model()->find(array("condition"=>"username = '" .$username. "'"));
			
			$route = $this->getRoute(); //get: module_id/controler_id/action_id
			
			$adminmenu = adminmenu::model()->find(array("condition"=>"route = '".$route."'"));
			
			if (!is_null($adminmenu))
				$this->session["adminmenu_id"] = $adminmenu->id;
			else
				$this->session["adminmenu_id"] = 0;
			
		}
	}
	
	function check_user_logged_in()
	{
		$user_logged_in = $this->session["user_logged_in"];	
		return $user_logged_in == 1;
	}
	
	function getUser($id = 0)
	{
		if ($id == 0) 
			return $this->user;
		else
			return user::model()->findByPk((int)$id);
	}
}